//
//  ScanViewController.m
//  SeaChat
//
//  Created by dllo on 16/6/15.
//  Copyright © 2016年 潘强. All rights reserved.
//

#import "ScanViewController.h"

#define width self.view.frame.size.width
#define height self.view.frame.size.height



@interface ScanViewController ()

@end

@implementation ScanViewController

-(void)dealloc{
    [_device release];
    [_input release];
    [_output release];
    [_session release];
    [_preview release];
    [_line release];
    [_lightButton release];
    [_detector release];

    [super dealloc];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}



- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"二维码扫描";
#pragma mark 左按钮
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemReply target:self action:@selector(leftAction:)];
#pragma mark 右按钮
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"相册" style:UIBarButtonItemStylePlain target:self action:@selector(rightAction:)];
    
#pragma mark 
    NSString *mediaType = AVMediaTypeVideo;
    
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
    
    if(authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied){
        NSLog(@"没有权限");
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"没有相机权限" message:@"请去设置-隐私-相机中对爱儿邦授权" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self.navigationController popViewControllerAnimated:YES];
        }];
        [alertController addAction:okAction];
        
        hasCameraRight = NO;
        return;
    }
    hasCameraRight = YES;
    
    imageView = [UIImageView new];
    imageView.image = [UIImage imageNamed:@"contact_scanframe"];
    [self.view addSubview:imageView];
    [imageView autoAlignAxis:ALAxisVertical toSameAxisOfView:self.view];
    [imageView autoPinEdgeToSuperviewEdge:ALEdgeTop withInset:100];
    [imageView autoSetDimensionsToSize:CGSizeMake(0.8 * width, 0.8 * width)];
    
    UILabel * labIntroudction= [UILabel new];
    labIntroudction.backgroundColor = [UIColor clearColor];
    labIntroudction.textColor=[UIColor whiteColor];
    labIntroudction.textAlignment = NSTextAlignmentCenter;
    labIntroudction.text=@"将取景框对准二维码，即自动扫描";
    [self.view addSubview:labIntroudction];
    [labIntroudction autoPinEdge:ALEdgeLeft toEdge:ALEdgeLeft ofView:imageView];
    [labIntroudction autoPinEdge:ALEdgeRight toEdge:ALEdgeRight ofView:imageView];
    [labIntroudction autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:imageView withOffset:8];
    
    
    self.lightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.lightButton.backgroundColor = [UIColor clearColor];
//    self.lightButton.frame = CGRectMake(0, 0, 80, 80);
    [self.view addSubview:self.lightButton];
    self.lightButton.layer.masksToBounds = YES;
    self.lightButton.layer.cornerRadius = 0.1 * width;
    [self.lightButton setImage:[UIImage imageNamed:@"shoudiantong"] forState:UIControlStateNormal];
    [_lightButton autoPinEdgeToSuperviewEdge:ALEdgeLeft withInset:(width *0.8) / 2];
    [_lightButton autoSetDimensionsToSize:CGSizeMake(0.2 * width, 0.2 * width)];
    [_lightButton autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:labIntroudction withOffset:20];
    [_lightButton addTarget:self action:@selector(lightButtonAc) forControlEvents:UIControlEventTouchUpInside];
    
    upOrdown = NO;
    num =0;
    _line = [UIImageView new];
    _line.image = [UIImage imageNamed:@"line"];
    [self.view addSubview:_line];
    [_line autoPinEdge:ALEdgeLeft toEdge:ALEdgeLeft ofView:imageView withOffset:40];
    [_line autoPinEdge:ALEdgeRight toEdge:ALEdgeRight ofView:imageView withOffset:-40];
    [_line autoSetDimension:ALDimensionHeight toSize:2];
    [_line autoPinEdge:ALEdgeTop toEdge:ALEdgeTop ofView:imageView withOffset:10];
#pragma mark 调用相机设置
    [self setupCamera];
    
    
    
    
    
    
}

-(void)leftAction:(UIBarButtonItem *)button{
    NSLog(@"我是返回按钮");

    [self.navigationController popToRootViewControllerAnimated:YES];
    



}

-(void)rightAction:(UIBarButtonItem *)button{

    NSLog(@"我是相册按钮");
    //获取本地相册
    [self readerImage];
    




}

#pragma mark 本地相册获取
- (void)readerImage{
    
//    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
//    
//    UIImagePickerController *photoPicker = [UIImagePickerController new];
//    photoPicker.delegate = self;
//    photoPicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
//    photoPicker.view.backgroundColor = [UIColor whiteColor];
//    
//    
//    [self presentViewController:photoPicker animated:YES completion:NULL];
//        
//    }else{
//    
//    
//        NSLog(@"打开失败");
//    }
    //初始化一个监听器
   self.detector = [CIDetector detectorOfType:CIDetectorTypeQRCode context:nil options:@{CIDetectorAccuracy : CIDetectorAccuracyHigh}];

    
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        
        UIImagePickerController *photoPicker = [UIImagePickerController new];
        photoPicker.delegate = self;
        //允许被编辑
        photoPicker.allowsEditing = YES;

        photoPicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        photoPicker.mediaTypes = [UIImagePickerController         availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeSavedPhotosAlbum];
        
       photoPicker.view.backgroundColor = [UIColor whiteColor];
        
        
        [self presentViewController:photoPicker animated:YES completion:NULL];
        
    }else{
        
        
        NSLog(@"打开失败");
    }

}

#pragma mark 协议方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
  
    
    //1 获取选择的图片
    UIImage *image = info[UIImagePickerControllerOriginalImage];
        //监测到的结果数组
    NSArray *features = [self.detector featuresInImage:[CIImage imageWithCGImage:image.CGImage]];
    NSLog(@".........%@",image);
    
   [picker dismissViewControllerAnimated:YES completion:^{
          if (features.count >= 1) {
            //结果对象
            CIQRCodeFeature *feature = [features objectAtIndex:0];
            NSString *scannedResult = feature.messageString;
            NSLog(@"成功====%@",scannedResult);
        
        }
        else
        {
            NSLog(@"失败");
            
                    UIAlertController *alter = [UIAlertController alertControllerWithTitle:@"提示" message:@"搜索不到" preferredStyle:UIAlertControllerStyleAlert];
            
                    UIAlertAction *otherAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            
                        [alter dismissViewControllerAnimated:YES completion:^{
            
                        }];
            
            
                        [self.navigationController popToRootViewControllerAnimated:YES];
            
                    }];
            
                    [alter addAction:otherAction];
                    
                    [self presentViewController:alter animated:YES completion:nil];
                }
            

       }];      
        

    
    
    
    
    
}



#pragma mark 音效震动
- (void)playBeep
{
    SystemSoundID soundID;
    
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"滴-2"ofType:@"mp3"]], &soundID);
    
    AudioServicesPlaySystemSound(soundID);
    
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
}



#pragma makr 设置照相机
- (void)setupCamera
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        // 耗时的操作
        // Device
        _device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
        NSLog(@"device == %@",_device);
        
        // Input
        _input = [AVCaptureDeviceInput deviceInputWithDevice:self.device error:nil];
        
        // Output
        _output = [[AVCaptureMetadataOutput alloc]init];
        //    [_output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
        [_output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
        
        // Session
        _session = [[AVCaptureSession alloc]init];
        [_session setSessionPreset:AVCaptureSessionPresetHigh];
        if ([_session canAddInput:self.input])
        {
            [_session addInput:self.input];
        }
        
        if ([_session canAddOutput:self.output])
        {
            [_session addOutput:self.output];
        }
        
        // 条码类型 AVMetadataObjectTypeQRCode
        _output.metadataObjectTypes =@[AVMetadataObjectTypeQRCode];
        dispatch_async(dispatch_get_main_queue(), ^{
            // 更新界面
            // Preview
            _preview =[AVCaptureVideoPreviewLayer layerWithSession:self.session];
            _preview.videoGravity = AVLayerVideoGravityResizeAspectFill;
            //    _preview.frame =CGRectMake(20,110,280,280);
            _preview.frame = self.view.bounds;
            [self.view.layer insertSublayer:self.preview atIndex:0];
            // Start
            [_session startRunning];
            
            
            [_output release];
            [_session release];
        });
    });
}





#pragma mark 扫描二维码 AVCaptureMetadataOutputObjectsDelegate
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    
    NSString *stringValue;
    
    if ([metadataObjects count] > 0)
    {
        AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex:0];
        stringValue = metadataObject.stringValue;
        
        [_session stopRunning];
        [timer invalidate];
        NSLog(@"%@",stringValue);
//扫描震动
        [self playBeep];
        
        if([stringValue hasPrefix:@"http://"]){
            
                      [_preview removeFromSuperlayer];
            
            UIView *vi = (UIView *)[self.view viewWithTag:1000];
            
            vi.hidden = YES;
            //用自己浏览器打开扫描结果
            
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:stringValue]];
            //扫描到结果后 跳转回去
            [self.navigationController popToRootViewControllerAnimated:NO];

        }else{
            
            [_preview removeFromSuperlayer];
            
            UIView *vi = (UIView *)[self.view viewWithTag:1000];
            
            vi.hidden = YES;
            
            UIAlertController *alter = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"无法识别" preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction *otherAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                
                [alter dismissViewControllerAnimated:YES completion:^{
                    
                }];
                
                vi.hidden = NO;
                
                self.tabBarController.tabBar.hidden = NO;
                
                [self.navigationController popToRootViewControllerAnimated:YES];
                
            }];
            
            [alter addAction:otherAction];
            
            [self presentViewController:alter animated:YES completion:nil];
            
        }
        
        
        //      if (stringValue.length > 0) {
        //           NSString *url = [NSURL URLWithString:@"html/judgement.html" relativeToURL:[ZXApiClient sharedClient].baseURL].absoluteString;
        //
        //            if ([stringValue hasPrefix:url]) {
        //                NSArray *arr = [stringValue componentsSeparatedByString:@"?"];
        //                if (arr.count > 1) {
        //                    NSString *uid = [[arr objectAtIndex:1] substringFromIndex:4];
        //
        //                    if (uid.integerValue == GLOBAL_UID) {
        //                        ZXMyProfileViewController *vc = [ZXMyProfileViewController viewControllerFromStoryboard];
        //                        [self.navigationController pushViewController:vc animated:YES];
        //                    } else {
        //                        ZXUserProfileViewController *vc = [ZXUserProfileViewController viewControllerFromStoryboard];
        //                        vc.uid = uid.integerValue;
        //                        [self.navigationController pushViewController:vc animated:YES];
        //                    }
        //                }
        //            }
        //            else if ([stringValue hasPrefix:[NSString stringWithFormat:@"%@qrcodelogin?qrcodeId=",@"http://www.aierbon.com/"]]) {
        //                NSString *qrcodeId = [[stringValue componentsSeparatedByString:@"="] lastObject];
        //                ZXLoginBackendViewController *vc = [ZXLoginBackendViewController viewControllerFromStoryboard];
        //                vc.qrcodeid = qrcodeId;
        //                [self.navigationController pushViewController:vc animated:YES];
        //            }
        //            else {
          //        [self.navigationController popViewControllerAnimated:YES];
//                       [[UIApplication sharedApplication] openURL:[NSURL URLWithString:stringValue]];
        //            }
        //        }
    }
    
}



#pragma mark 灯光按钮
-(void)lightButtonAc{
    
    
    _device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    NSError *error;
    if (_device.hasTorch) {  // 判断设备是否有闪光灯
        BOOL b = [_device lockForConfiguration:&error];
        if (!b) {
            if (error) {
                NSLog(@"lock torch configuration error:%@", error.localizedDescription);
            }
            return;
        }
        _device.torchMode = (_device.torchMode == AVCaptureTorchModeOff ? AVCaptureTorchModeOn : AVCaptureTorchModeOff);
        [_device unlockForConfiguration];
    }
    
    
}



- (BOOL)navigationShouldPopOnBackButton
{
    [timer invalidate];
    return YES;
}


-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    if (hasCameraRight) {
        if (_session && ![_session isRunning]) {
            [_session startRunning];
        }
        timer = [NSTimer scheduledTimerWithTimeInterval:.02 target:self selector:@selector(animation1) userInfo:nil repeats:YES];
    }
}

//- (void)viewWillDisappear:(BOOL)animated
//{
//    [super viewWillDisappear:animated];
//    [timer invalidate];
//}
#pragma mark 扫描线
-(void)animation1
{
    if (upOrdown == NO) {
        num ++;
        _line.frame = CGRectMake(CGRectGetMinX(_line.frame), 110+2*num, CGRectGetWidth(_line.frame), CGRectGetHeight(_line.frame));
        if (2 * num == CGRectGetHeight(imageView.frame) - 20) {
            upOrdown = YES;
        }
    }
    else {
        num --;
        _line.frame = CGRectMake(CGRectGetMinX(_line.frame), 110+2*num, CGRectGetWidth(_line.frame), CGRectGetHeight(_line.frame));
        if (num == 0) {
            upOrdown = NO;
        }
    }
    
}




@end
